package com.zlt.miaosha.exception;

import com.zlt.miaosha.result.CodeMsg;
import com.zlt.miaosha.result.Result;
import org.omg.CORBA.CODESET_INCOMPATIBLE;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zhoulitong
 * @date 2018/6/14
 * @description
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value=Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request,Exception e){
        //将异常信息打印到控制台
        e.printStackTrace();
        //处理业务异常
        if (e instanceof GlobalException){
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getCm());
        }
        //处理校验异常
        else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            //可能有很多错误
            List<ObjectError> errors = ex.getAllErrors();
            //取出其中的一个
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        } else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
